<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>重置密码</span>
    </div>
    <!-- 表单 -->
    <el-form :model="pwdForm" :rules="pwdFormRules" ref="pwdFormRef" label-width="100px">
      <el-form-item label="原密码" prop="old_pwd">
        <el-input v-model="pwdForm.old_pwd" type="password"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="new_pwd">
        <el-input v-model="pwdForm.new_pwd" type="password"></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="re_pwd">
        <el-input v-model="pwdForm.re_pwd" type="password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updataPwd">修改密码</el-button>
        <el-button @click="$refs.pwdFormRef.resetFields()">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
export default {
  name: 'UserPwd',
  data() {
    // 自定义检验规则: 新旧密码不能相同
    const samePwd = (rule, value, cd) => {
      if (value === this.pwdForm.old_pwd) {
        cd(new Error('与新旧密码不能一致 !'))
      } else {
        cd()
      }
    }

    // 自定义检验规则: 两次密码必须一致
    const rePwd = (rule, value, cd) => {
      if (value === this.pwdForm.new_pwd) {
        cd()
      } else {
        cd(new Error('两次密码不一样 !'))
      }
    }

    return {
      // 表单的数据对象
      pwdForm: {
        old_pwd: '',
        new_pwd: '',
        re_pwd: ''
      },
      // 表单的验证规则对象
      // 验证规则的名字, 必须和数据项的名字保持一致
      pwdFormRules: {
        // 必填项的检验
        old_pwd: [
          { required: true, message: '旧密码不能为空', trigger: 'blur' },
          { pattern: /^\S{6,15}$/, message: '密码长度必须是6-15位的非空字符', trigger: 'blur' }
        ],
        new_pwd: [
          { required: true, message: '新密码不能为空', trigger: 'blur' },
          { pattern: /^\S{6,15}$/, message: '密码长度必须是6-15位的非空字符', trigger: 'blur' },
          // 自定义新旧密码的校验
          { validator: samePwd, trigger: 'blur' }
        ],
        re_pwd: [
          { required: true, message: '清确认新密码', trigger: 'blur' },
          { pattern: /^\S{6,15}$/, message: '密码长度必须是6-15位的非空字符', trigger: 'blur' },
          // 自定义两次密码的校验
          { validator: rePwd, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    updataPwd() {
      this.$refs.pwdFormRef.validate(async valid => {
        if (!valid) return
        // console.log('更新成功')
        const { data: res } = await this.$http.patch('/my/updatepwd', this.pwdForm)
        if (res.code !== 0) return this.$message.error('更新密码失败！')

        this.$message.success('更新密码成功！')
        this.$refs.pwdFormRef.resetFields()
        this.$router.push('/login')
        this.$store.commit('updateToken', '')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  width: 500px;
}
</style>
